const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const db = require('../config/database');
const logger = require('../config/logger');
const { logInfo, logError, logWarning } = require('../utils/systemLogger');

/**
 * 管理员登录
 */
exports.adminLogin = async (req, res) => {
  try {
    const { username, password } = req.body;

    // 查询管理员
    const [admins] = await db.query(
      'SELECT * FROM admins WHERE username = ?',
      [username]
    );

    if (admins.length === 0) {
      // 记录失败的登录尝试
      await logWarning('login_failed', `管理员登录失败: 用户名不存在 (${username})`, {
        ipAddress: req.ip
      });

      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    const admin = admins[0];

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, admin.password);

    if (!isPasswordValid) {
      // 记录失败的登录尝试
      await logWarning('login_failed', `管理员登录失败: 密码错误 (${username})`, {
        userId: admin.id,
        userType: 'admin',
        ipAddress: req.ip
      });

      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 更新最后登录信息
    await db.query(
      'UPDATE admins SET last_login_at = NOW(), last_login_ip = ? WHERE id = ?',
      [req.ip, admin.id]
    );

    // 生成JWT token
    const token = jwt.sign(
      {
        id: admin.id,
        username: admin.username,
        type: 'admin'
      },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRE || '24h' }
    );

    logger.info(`管理员 ${username} 登录成功`);

    // 记录系统日志
    await logInfo('login', `管理员 ${username} 登录成功`, {
      userId: admin.id,
      userType: 'admin',
      ipAddress: req.ip
    });

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          id: admin.id,
          username: admin.username,
          email: admin.email
        }
      }
    });
  } catch (error) {
    logger.error('管理员登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败'
    });
  }
};

/**
 * 用户注册
 */
exports.userRegister = async (req, res) => {
  try {
    const { username, password, email, nickname } = req.body;

    // 验证必填字段
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }

    // 验证用户名长度
    if (username.length < 3 || username.length > 20) {
      return res.status(400).json({
        success: false,
        message: '用户名长度必须在3-20个字符之间'
      });
    }

    // 验证密码长度
    if (password.length < 6) {
      return res.status(400).json({
        success: false,
        message: '密码长度不能少于6个字符'
      });
    }

    // 检查用户名是否已存在
    const [existingUsers] = await db.query(
      'SELECT id FROM users WHERE username = ?',
      [username]
    );

    if (existingUsers.length > 0) {
      return res.status(400).json({
        success: false,
        message: '用户名已被注册'
      });
    }

    // 如果提供了邮箱，检查邮箱是否已被使用
    if (email) {
      const [existingEmails] = await db.query(
        'SELECT id FROM users WHERE email = ?',
        [email]
      );

      if (existingEmails.length > 0) {
        return res.status(400).json({
          success: false,
          message: '邮箱已被注册'
        });
      }
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 插入新用户（不包含client_id，稍后由客户端上传）
    const [result] = await db.query(
      `INSERT INTO users (username, password, email, nickname, status, is_online, created_at)
       VALUES (?, ?, ?, ?, 1, 0, NOW())`,
      [username, hashedPassword, email || null, nickname || username]
    );

    logger.info(`新用户注册成功: ${username}`);

    // 记录系统日志
    await logInfo('user_register', `新用户注册: ${username}`, {
      userId: result.insertId,
      userType: 'user',
      ipAddress: req.ip
    });

    res.json({
      success: true,
      message: '注册成功',
      data: {
        id: result.insertId,
        username
      }
    });
  } catch (error) {
    logger.error('用户注册失败:', error);
    res.status(500).json({
      success: false,
      message: '注册失败'
    });
  }
};

/**
 * 客户端用户登录
 */
exports.userLogin = async (req, res) => {
  try {
    const { username, password } = req.body;

    // 查询用户
    const [users] = await db.query(
      'SELECT * FROM users WHERE username = ? AND status = 1',
      [username]
    );

    if (users.length === 0) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误或账号已被禁用'
      });
    }

    const user = users[0];

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);

    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 只更新最后登录信息（不更新is_online，由WebSocket控制）
    await db.query(
      'UPDATE users SET last_online_at = NOW(), last_ip = ? WHERE id = ?',
      [req.ip, user.id]
    );

    // 生成JWT token
    const token = jwt.sign(
      {
        id: user.id,
        username: user.username,
        type: 'user'
      },
      process.env.JWT_SECRET,
      { expiresIn: process.env.JWT_EXPIRE || '24h' }
    );

    logger.info(`用户 ${username} 登录成功`);

    // 记录系统日志
    await logInfo('login', `用户 ${username} 登录成功`, {
      userId: user.id,
      userType: 'user',
      ipAddress: req.ip
    });

    res.json({
      success: true,
      message: '登录成功',
      data: {
        token,
        user: {
          id: user.id,
          username: user.username,
          nickname: user.nickname,
          avatar_url: user.avatar_url || null
        }
      }
    });
  } catch (error) {
    logger.error('用户登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败'
    });
  }
};

/**
 * 🔥 上传客户端ID（登录成功后调用）
 */
exports.uploadClientId = async (req, res) => {
  try {
    const { id, username, type } = req.user;
    const { client_id } = req.body;

    // 验证client_id
    if (!client_id) {
      return res.status(400).json({
        success: false,
        message: '客户端ID不能为空'
      });
    }

    // 只允许普通用户上传客户端ID
    if (type !== 'user') {
      return res.status(403).json({
        success: false,
        message: '权限不足'
      });
    }

    // 查询当前用户信息
    const [users] = await db.query(
      'SELECT client_id, is_online FROM users WHERE id = ?',
      [id]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    const user = users[0];

    // 🔥 检查是否已在其他客户端登录
    if (user.client_id && user.client_id !== client_id && user.is_online === 1) {
      logger.warn(`用户 ${username} 已在客户端 ${user.client_id} 登录，将强制旧客户端下线`);
      
      // 通过WebSocket通知旧客户端强制登出
      try {
        const socketManager = req.app.get('socketManager');
        if (socketManager) {
          // 发送强制登出事件到旧客户端
          socketManager.forceLogout(user.client_id, '该账号已在其他设备登录');
          logger.info(`已通知旧客户端 ${user.client_id} 强制下线`);
        }
      } catch (error) {
        logger.error('通知旧客户端下线失败:', error);
      }
      
      // 记录系统日志
      await logWarning('force_logout', `用户 ${username} 在新客户端 ${client_id} 登录，旧客户端 ${user.client_id} 被强制下线`, {
        userId: id,
        userType: 'user',
        oldClientId: user.client_id,
        newClientId: client_id,
        ipAddress: req.ip
      });
    }

    // 更新客户端ID和在线状态
    await db.query(
      'UPDATE users SET client_id = ?, is_online = 1, last_online_at = NOW(), last_ip = ? WHERE id = ?',
      [client_id, req.ip, id]
    );

    logger.info(`用户 ${username} 上传客户端ID: ${client_id}`);

    // 记录系统日志
    await logInfo('upload_client_id', `用户 ${username} 上传客户端ID: ${client_id}`, {
      userId: id,
      userType: 'user',
      clientId: client_id,
      ipAddress: req.ip
    });

    res.json({
      success: true,
      message: '客户端ID上传成功'
    });
  } catch (error) {
    logger.error('上传客户端ID失败:', error);
    res.status(500).json({
      success: false,
      message: '上传客户端ID失败'
    });
  }
};

/**
 * 退出登录
 */
exports.logout = async (req, res) => {
  try {
    const { id, type } = req.user;

    // 如果是普通用户，更新在线状态
    if (type === 'user') {
      await db.query(
        'UPDATE users SET is_online = 0 WHERE id = ?',
        [id]
      );
    }

    logger.info(`用户 ${req.user.username} 退出登录`);

    // 记录系统日志
    await logInfo('logout', `用户 ${req.user.username} 退出登录`, {
      userId: id,
      userType: type,
      ipAddress: req.ip
    });

    res.json({
      success: true,
      message: '退出成功'
    });
  } catch (error) {
    logger.error('退出登录失败:', error);
    res.status(500).json({
      success: false,
      message: '退出失败'
    });
  }
};
